/**
 * 
 */
package com.base.http;

import android.content.Context;

import com.base.control.MActivitySupport;
import com.base.control.RequestCallback;
import com.base.model.Bean2Json;
import com.base.util.ConstantResource;
import com.base.util.DateUtil;
import com.base.util.Helper;
import com.base.util.MLog;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.RequestParams;

import java.math.BigDecimal;
import java.util.Date;
import java.util.Map;

/**
 * 接口调用逻辑层
 * 
 * @author yjh
 * 
 */
public class ApiClient {
	private static AsyncHttpClient client = new AsyncHttpClient();
	private ParamsFormat pf;
	private Bean2Json<?> b2jData;
	
	public static void getApiData(MActivitySupport context, RequestCallback controller, String methodName, ParamsFormat pf, Bean2Json<?> b2jData, boolean isShowToast) {
		ApiClient client = new ApiClient();
		client.pf = pf;
		client.b2jData = b2jData;
		client.getApiData(context, controller, methodName, isShowToast);
	}

    public static void getApiData(MActivitySupport context, RequestCallback controller, String methodName, ParamsFormat pf, Bean2Json<?> b2jData) {
        getApiData(context, controller, methodName, pf, b2jData, true);
    }

	public void getApiData(MActivitySupport context, RequestCallback controller, String methodName, boolean isShowToast) {
		MJsonResponseHandler handler = new MJsonResponseHandler(context, controller, b2jData, methodName, isShowToast);
        try {
			client.post(ConstantResource.URL, makeURL(pf), handler);
		} catch (Exception e) {
            controller.onRequestError(0, "");
			MLog.d(controller.getClass().getSimpleName() + "" + e.getClass().getName());
            if(isShowToast)
			    Helper.toast(context, ConstantResource.INTERFACE_ERROR + "apidata");
		}
	}
	
	public static void getApiFile(String url, RequestCallback callback) {
		MBinaryResponseHandler handler = new MBinaryResponseHandler(callback);
        try {
            client.get(url, handler);
        } catch (Exception e) {
            MLog.e(e);
        }
	}
	
	private static RequestParams makeURL(ParamsFormat obj) throws Exception {
		RequestParams params = new RequestParams();
		//封装基本参数
        params.put("appid", ConstantResource.APPID);
		params.put("deviceid", ConstantResource.getDeviceid());
		params.put("methodno", obj.getMethodno());
		params.put("userid", ConstantResource.USERID);
		params.put("verify", ConstantResource.VERIFY);
		MLog.d(params.toString());
		for(Map.Entry<String, Object> e: obj.getParams().entrySet()) {
			Object o = e.getValue();
			if(o != null) {
//                if((e.getKey().equalsIgnoreCase("password") || e.getKey().equals("passwd")) && o instanceof String) {
//                    String password = MD5.md5(ConstantResource.MD5_KEY + (String)o); //md5
//                    o = password;
//                }
				if(o instanceof Date) {//格式化日期
					params.put(e.getKey(), DateUtil.dateToStr((Date)o, "yyyy-MM-dd HH:mm:ss"));
				} else if(!isBasicData(o)) {
					params.remove(e.getKey());
				} else {
					params.put(e.getKey(), o);
				}
			}
		}
		
		MLog.d(params.toString());
		return params;
	}
	
	
	
	@SuppressWarnings("rawtypes")
	public static boolean isBasicData(Object o) {
		if(o == null)
			return false;
		Class clz = o.getClass();
		return clz.equals(Integer.TYPE) || clz.equals(Long.TYPE)
		|| clz.equals(String.class) || clz.equals(Double.TYPE)
		|| clz.equals(Short.TYPE) || clz.equals(Character.TYPE)
		|| clz.equals(Boolean.TYPE) || clz.equals(Byte.TYPE) || clz.equals(Float.TYPE)
		|| clz.equals(Long.class) || clz.equals(BigDecimal.class)
		|| clz.equals(Integer.class) || clz.equals(Float.class) 
		|| clz.equals(Byte.class) || clz.equals(Boolean.class)
		|| clz.equals(Short.class) || clz.equals(Character.class)
		|| clz.equals(Double.class);
	}
	
	/**
	 * 关闭该context下的请求
	 * @param context
	 * @param mayInterruptIfRunning
	 */
	public static void closeReq(final Context context, final boolean mayInterruptIfRunning) {
//		new Thread(new Runnable() {
//			
//			@Override
//			public void run() {
//				// TODO Auto-generated method stub
//				
//			}
//		});
		client.cancelRequests(context, mayInterruptIfRunning);
	}

	public ParamsFormat getPf() {
		return pf;
	}

	public void setPf(ParamsFormat pf) {
		this.pf = pf;
	}

	public Bean2Json<?> getB2jData() {
		return b2jData;
	}

	public void setB2jData(Bean2Json<?> b2jData) {
		this.b2jData = b2jData;
	}
	
}
